<?php
/**
 * 八爪鱼采集器
 * 记得对接钉钉
 * */

namespace App\Services\Common;

use App\Imports\AmazonCommentImport;
use App\Models\Assess\EvaluationMonitorConnectModel;
use App\Models\Assess\EvaluationMonitoringModel;
use App\Models\Assess\PythonTaskModel;
use App\Services\BaseService;
use Illuminate\Support\Facades\Log;

class AmazonComment extends BaseService
{
    //登录用户名
    public $userName = 'bigxiaoren';
    //登录密码
    public $password = 'wuyu123456';
    //固定值 必填
    public $grantType = 'password';

    public $baZhuaYuUrl = 'https://dataapi.bazhuayu.com';

    //评论需要转换的字段
    public $filedChina = [
        'evaluation_title' => '标题',
        'look' => '查看',
        'evaluation_connent' => '查看1',
        'stars' => 'aiconalt',
        'evaluation_user' => '名称',
        'evaluation_user_profile' => 'aprofile_链接',
        'title_link' => '标题链接',
        'comment_image' => '查看2'
    ];

    //得分和评论数对应的字段
    public $filedStars = [
        'stars'=>'星级',
        'reviews_ratings'=>'得分和评论数',
        'title'=>'标题',
        'image'=>'图片链接',
    ];


    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new EvaluationMonitoringModel();
    }

    /**
     * @Notes:获取八爪鱼token
     * @Interface getBaZhuaYuToken
     * @author: wuyu
     * @Time: 2023/5/29   16:25
     */
    public function getBaZhuaYuToken()
    {
        try {
            $url = $this->baZhuaYuUrl . '/token';
            $requestData = [
                'username' => $this->userName,
                'password' => $this->password,
                'grant_type' => $this->grantType,
            ];
            $response = curl_post($url, $requestData);
            if (empty($response)) throw new \Exception($response);
            $responseData = json_decode($response, true);
            return $responseData['access_token'] ?? '';
        } catch (\Exception $e) {
            Log::channel('bazhuayuLog')->debug('bazhuayu获取令牌失败:' . $e->getMessage() . ' ' . $e->getFile() . ' ' . $e->getLine());
        }
        return '';
    }

    /**
     * @Notes:获取八爪鱼抓取的amzon评论信息
     * @Interface getBaZhuaYuTaskId
     * @author: wuyu
     * @Time: 2023/5/29   16:20
     */
    public function getBaZhuaYuComment($params)
    {

        $token = $this->getBaZhuaYuToken();
        try {
//            Log::channel('bazhuayuLog')->debug('getBaZhuaYuComment准备接受采集数据:');
            //获取需要导出的taskId
            $PythonTaskModel = new PythonTaskModel();
            $EvaluationMonitoringModel = new EvaluationMonitoringModel();
            $EvaluationMonitorConnectModel = new EvaluationMonitorConnectModel();
            $AmazonCommentImport = new AmazonCommentImport();
            $taskId = $params['task_id'] ?? '';

            $model = $PythonTaskModel->where('task_type', '=', 1)->where('mark', '=', 1);
            if (!empty($taskId)) $model->where('task_id','=',$taskId);
            $taskData = $model->get()->toArray();

            foreach ($taskData as $val) {

                //添加评价监控信息
                $monitorData = $EvaluationMonitoringModel->getOne([
                    ['asin', '=', $val['asin']],
                    ['mark', '=', 1],
                ]);
                if (empty($monitorData)) continue;

                $monitorId = $monitorData['id'];

                $url = $this->baZhuaYuUrl . '/api/notexportdata/gettop';
                $requestData = [
                    'taskId' => $val['task_id'],
                    'size' => 1000,
                ];
                $response = curl_get($url, $requestData, ['bazhuayu_token' => $token]);
                if (empty($response)) {
                    Log::channel('bazhuayuLog')->debug('getBaZhuaYuTaskId请求参数:'.$requestData);
                    Log::channel('bazhuayuLog')->debug('getBaZhuaYuTaskId获取数据失败:'.$response);
                    continue;
                }
                $requestData = json_decode($response, true);
                $dataList = $requestData['data']['dataList'] ?? [];
                if (empty($dataList)) continue;

                foreach ($dataList as $vv){
                    $filedChina = $this->filedChina;
                    $fieldList = [];
                    foreach ($filedChina as $fieldK=>$fieldV){
                        $fieldList[$fieldK] = $vv[$fieldV] ?? '';
                        if ($fieldK == 'stars') $fieldList[$fieldK] = intval($fieldList[$fieldK]);
                    }
                    // 空数据进行处理
                    if (empty($fieldList['evaluation_user'])) continue;

                    $lookExp = explode(' ',$fieldList['look']);
                    if (count($lookExp)>=3 && strpos($fieldList['look'],'年') !==false){
                        $commentTime = $lookExp[1] ?? '';
                        $commentTime = str_replace(['年','月'], '-', $commentTime);
                        $commentTime = str_replace(['日'], '', $commentTime);
                        $fieldList['evaluation_time'] = $commentTime;
                    }elseif(strpos($fieldList['look'],'年') !==false){
                        $commentTime = $lookExp[0] ?? '';
                        $commentTime = str_replace(['年','月'], '-', $commentTime);
                        $commentTime = str_replace(['日'], '', $commentTime);
                        $fieldList['evaluation_time'] = $commentTime;
                    }elseif(strpos($fieldList['look'],'Reviewed in') !==false){
                        $commentTime = $lookExp[1] ?? '';
                        $fieldList['evaluation_time'] = $commentTime;
                    }

                    if (strpos($fieldList['evaluation_time'],'年') ===false){
                        $lookExp = explode(' on ',$fieldList['look']);
                        if (count($lookExp)>=2){
                            $commentTime = $lookExp[1] ?? '';
                            $commentTime = str_replace([', '], ' ', $commentTime);
                            $commentTimeExp = explode(' ',$commentTime);
                            $month = $commentTimeExp[0] ?? '';
                            $day = $commentTimeExp[1] ?? '';
                            $year = $commentTimeExp[2] ?? '';
                            $fieldList['evaluation_time'] = $year.'-'.($AmazonCommentImport->month_abbr_list[$month] ?? '').'-'.$day;
                        }
                    }else{
                        $commentTime = $lookExp[0] ?? '';
                        $commentTime = str_replace(['年','月'], '-', $commentTime);
                        $commentTime = str_replace(['日'], '', $commentTime);
                        $fieldList['evaluation_time'] = $commentTime;
                    }

                    if (isset($fieldList['look'])) unset($fieldList['look']);
                    //判断是否存在
                    $monitorConnectExists = $EvaluationMonitorConnectModel->getOne([
                        ['evaluation_monitor_id', '=', $monitorId],
                        ['evaluation_title', '=', $fieldList['evaluation_title']],
                        ['evaluation_user', '=', $fieldList['evaluation_user']],
                        ['evaluation_time', '=', $fieldList['evaluation_time']],
                        ['mark', '=', 1],
                    ]);

                    if (empty($monitorConnectExists)){
                        $fieldList['create_time'] = time();
                        $fieldList['evaluation_monitor_id'] = $monitorId;
                        $EvaluationMonitorConnectModel->insert($fieldList);
                    }
                }
                //标记正在导出为已导出
                $updateUrl = $this->baZhuaYuUrl . '/api/notexportdata/update?taskId='.$val['task_id'];
                $updateResponse = curl_post($updateUrl, [], ['bazhuayu_token' => $token]);

            }

        }catch (\Exception $e){
            Log::channel('bazhuayuLog')->debug('getBaZhuaYuTaskId捕获异常:' . $e->getMessage() . ' ' . $e->getFile() . ' ' . $e->getLine());
        }

    }


    /**
     * @Notes:获取八爪鱼抓取的amzon的星级
     * @Interface getBazhuaYuStars
     * @param $params
     * @author: wuyu
     * @Time: 2023/5/30   18:33
     */
    public function getBazhuaYuStars($params)
    {

        $token = $this->getBaZhuaYuToken();

        try {
            Log::channel('bazhuayuLog')->debug('getBazhuaYuStars准备接受采集数据:');
            //获取需要导出的taskId
            $PythonTaskModel = new PythonTaskModel();
            $EvaluationMonitoringModel = new EvaluationMonitoringModel();
            $taskId = $params['task_id'] ?? '';

            $model = $PythonTaskModel->where('task_type', '=', 2)->where('mark', '=', 1);
            if (!empty($taskId)) $model->where('task_id','=',$taskId);
            $taskData = $model->get()->toArray();

            foreach ($taskData as $val) {

                //添加评价监控信息
                $monitorData = $EvaluationMonitoringModel->getOne([
                    ['asin', '=', $val['asin']],
                    ['mark', '=', 1],
                ]);
                if (empty($monitorData)) continue;

                $monitorId = $monitorData['id'];

                $url = $this->baZhuaYuUrl . '/api/notexportdata/gettop';
                $requestData = [
                    'taskId' => $val['task_id'],
                    'size' => 1,
                ];
                $response = curl_get($url, $requestData, ['bazhuayu_token' => $token]);
                if (empty($response)) {
                    Log::channel('bazhuayuLog')->debug('getBaZhuaYuTaskId请求参数:' . $requestData);
                    Log::channel('bazhuayuLog')->debug('getBaZhuaYuTaskId获取数据失败:' . $response);
                    continue;
                }
                $requestData = json_decode($response, true);
                $dataList = $requestData['data']['dataList'] ?? [];
                if (empty($dataList)) continue;

                foreach ($dataList as $vv){
                    $filedStars = $this->filedStars;
                    $filedStarsList = [];
                    foreach ($filedStars as $fieldK=>$fieldV){
                        $filedStarsList[$fieldK] = $vv[$fieldV] ?? '';
                        if ($fieldK == 'reviews_ratings') $filedStarsList[$fieldK] = strip_html_tags($filedStarsList[$fieldK]);
                    }

                    if (empty($filedStarsList['stars'])) continue;

                    $filedStarsList['reviews_ratings'] = ltrim(rtrim($filedStarsList['reviews_ratings'],' '),' ');
                    $filedStarsList['reviews_ratings'] = str_replace([' total ratings',' with reviews',' 总评分',' 带评论',','],'',$filedStarsList['reviews_ratings']);
                    $filedStarsList['stars'] = str_replace([' out of 5','星，共 5 星'],'',$filedStarsList['stars']);
                    $reviewsRatings = explode(' ',$filedStarsList['reviews_ratings']);
                    if (!empty($reviewsRatings[0])) $filedStarsList['ratings'] = intval($reviewsRatings[0]);
                    if (!empty($reviewsRatings[1])) $filedStarsList['reviews'] = intval($reviewsRatings[1]);
                    unset($filedStarsList['reviews_ratings']);
                    $filedStarsList['update_time'] = time();
                    $EvaluationMonitoringModel->where('id', '=', $monitorId)->update($filedStarsList);
                    $EvaluationMonitoringModel->cacheReset($monitorId, $filedStarsList, $monitorId);
                }
                //标记正在导出为已导出
                $updateUrl = $this->baZhuaYuUrl . '/api/notexportdata/update?taskId='.$val['task_id'];
                curl_post($updateUrl, [], ['bazhuayu_token' => $token]);
            }

        }catch (\Exception $e){
            Log::channel('bazhuayuLog')->debug('getBazhuaYuStars捕获异常:' . $e->getMessage() . ' ' . $e->getFile() . ' ' . $e->getLine());
        }

    }


}
